package cfs.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import cfs.databean.Fund;
import cfs.formbean.FundForm;
import cfs.model.FundDAO;
import cfs.model.Model;

/**
 * 
 * @author danny seow
 */
public class CreateFundAction extends Action {
	private FormBeanFactory<FundForm> formBeanFactory = FormBeanFactory
			.getInstance(FundForm.class);

	private FundDAO fundDAO;

	public CreateFundAction(Model model) {
		fundDAO = model.getFundDao();
	}

	@Override
	public String getName() {
		return "createFund.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		FundForm form;
		try {
			form = formBeanFactory.create(request);
			request.setAttribute("form", form);

			if (!form.isPresent()) {
				return "CreateFundPage.jsp";
			}
			// Validation of forms for errors
			// Fund fundReturned = fundDAO.lookup(form.getSymbol());
			// if (fundReturned != null) {
			// errors.add("Fund Already Exists");
			// }
			if (fundDAO.isFundExist(form.getSymbol())) {
				errors.add("Fund Already Exists");
			}

			errors.addAll(form.getValidationErrors());
			if (errors.size() > 0) {
				return "CreateFundPage.jsp";
			}

			Fund fund = new Fund();
			String fundName = request.getParameter("name");
			String fundSymbol = request.getParameter("symbol");
			fund.setName(fundName);
			fund.setSymbol(fundSymbol);
			fundDAO.create(fund);

			String successStatement = "Fund " + fund.getSymbol()
					+ " have been created!";
			
			request.setAttribute("successState", successStatement);
			return "viewFundList.do";

		} catch (FormBeanException ex) {
			errors.add("Funds have already been created");
			Logger.getLogger(CreateFundAction.class.getName()).log(
					Level.SEVERE, null, ex);
			return "CreateFundPage.jsp";
		} catch (DAOException e) {
			errors.add("Funds could not be created.");
			return "CreateFundPage.jsp";
		}
	}
}
